package com.lagou.edu.controller;

import com.lagou.edu.constant.CodeValidateResult;
import com.lagou.edu.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserService userService;

    @Reference
    private CodeRpcService codeRpcService;

    // 注册接⼝，true成功，false失败
    @GetMapping("/register/{email}/{password}/{code}")
    public int register(@PathVariable("email") String email, @PathVariable("password") String password, @PathVariable("code") String code,
        HttpServletResponse response) {
        System.out.println("注册账号: email=" + email + " pwd=" + password + " code=" + code);
        // 调用code微服务，检查验证码是否有效
        int status = codeRpcService.validate(email, code);
        log.info("校验结果：{}", status);
        // 注册成功，根据 <⽤户邮箱+密码> ⽣成签发token令牌（此处⽣成⼀个UUID模拟即可）
        if (status == CodeValidateResult.CORRECT) {
            // 添加用户
            userService.addUser(email, password);
            // 生成token
            String token = UUID.randomUUID().toString();
            log.info("为邮箱[{}]生成token：{}", email, token);
            // 保存token到数据库
            tokenService.save(email, token);
            // 添加到cookie
            Cookie cookie = new Cookie("token", token);
            // 这里必须setPath为根路径
            cookie.setPath("/");
            response.addCookie(cookie);
        }

        return status;
    }

    // 是否已注册，根据邮箱判断。true代表已经注册过，false代表尚未注册
    @GetMapping("/isRegistered/{email}")
    public boolean isRegistered(@PathVariable("email") String email) {
        return userService.emailRegistered(email);
    }

    // 登录接⼝，验证⽤户名密码合法性，根据⽤户名和密码⽣成token，token存⼊数据库，并写⼊cookie中，登录成功返回邮箱地址，重定向到欢迎⻚
    @GetMapping("/login/{email}/{password}")
    public String login(@PathVariable("email") String email, @PathVariable("password") String password,
                        HttpServletResponse response) {
        System.out.println("login：email=" + email + " pwd=" + password);

        // 登录成功
        if (userService.findByEmailAndPwd(email, password) != null) {
            // 生成token
            String token = UUID.randomUUID().toString();
            log.info("登录成功！email={}, token={}", email, token);
            // 保存到数据库
            tokenService.save(email, token);
            // 添加到cookie
            Cookie cookie = new Cookie("token", token);
            // 这里必须setPath为根路径
            cookie.setPath("/");
            response.addCookie(cookie);
            return email;
        }
        return "false";
    }

    // 据token查询⽤户登录邮箱接⼝
    @GetMapping("info/{token}")
    public String getInfo(@PathVariable("token") String token) {
        System.out.println("getInfo by token：" + token);
        return tokenService.findByToken(token).getEmail();
    }

}
